package com.shanghai.market.plshnaghai.net;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.shanghai.market.plshnaghai.AppApplication;
import com.shanghai.market.plshnaghai.entity.AppData;
import com.shanghai.market.plshnaghai.entity.PtResponse;
import com.shanghai.market.plshnaghai.listeners.OnResultListener;
import com.shanghai.market.plshnaghai.publics.LogCat;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * 业务基类
 */
final public class Manager<T extends PtResponse> {
    private VolleyParams params;
    private VolleyParams headers;

    private Type mType;
    private OnResultListener<T> onResultListener;
    /**
     * 连接是否己经结束
     */
    private boolean isFinished = true;
    private static final int VOLLEY_TIMEOUT = 50 * 1000;

    public Manager() {
        super();
        this.params = new VolleyParams();
        this.headers = AppApplication.getInstance().initHttpHeader();
    }

    public void setParams(VolleyParams params) {
        this.params = params;
    }

    public VolleyParams getParams() {
        return params;
    }

    public void setOnResultListener(OnResultListener<T> onResultListener) {
        this.onResultListener = onResultListener;
    }

    public void setType(Type type) {
        this.mType = type;
    }

    public void executeRequest(int method, String url) {
        if (!isFinished) {
            return;
        }

        isFinished = false;
        LogCat.i("url:" + url);
        LogCat.i("params:" + params);
        LogCat.i("headers:" + headers);

        final StringRequest request = new StringRequest(method, url, responseListener(), errorListener()) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String cookie = response.headers.get("Set-Cookie");
                if (null != cookie) {
                    AppData data = AppApplication.getInstance().getAppData();
                    data.setCookie(cookie);
                    AppApplication.getInstance().saveAppData(data);
                    data = null;
                }
                return super.parseNetworkResponse(response);
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return headers;
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(VOLLEY_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        RequestManager.addRequest(request, this);
    }

    public void cancelAll() {
        RequestManager.cancelAll(this);
    }

    private void handleSuccessResult(T body) {
        isFinished = true;
        if (this.onResultListener != null) {
            this.onResultListener.onSuccess(body);
        }
    }

    private void handleFailResult(String text) {
        isFinished = true;
        if (this.onResultListener != null) {
            this.onResultListener.onFail(text);
        }
    }

    private ErrorListener errorListener() {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error instanceof TimeoutError) {
                    handleFailResult("网络连接超时！");
                } else if (error instanceof ServerError) {
                    handleFailResult("连接服务器异常！");
                } else if (error instanceof AuthFailureError) {
                    handleFailResult("连接服务器异常！");
                } else if (error instanceof NetworkError) {
                    handleFailResult("网络未连接！");
                } else if (error instanceof NoConnectionError) {
                    handleFailResult("网络未连接！");
                } else {
                    handleFailResult("连接服务器异常！");
                }
            }
        };
    }

    private Listener<String> responseListener() {
        final Listener<String> listener = new Listener<String>() {

            @Override
            public void onResponse(String result) {
                LogCat.i("Manager success:" + result);
                final Gson gson = new Gson();
                final T t = gson.fromJson(result, mType);
                if (t == null) {
                    handleFailResult("获取数据失败！");
                    return;
                }
                String message = t.getErrorMessage();
                final String status = t.getStatus();
                if ("ok".equals(status)) {
                    handleSuccessResult(t);
                } else {
                    handleFailResult(message);
                }
            }

        };
        return listener;
    }

}
